package com.yugao.fintech.antelope.system.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.system.mapper.SysRoleMenuRelMapper;
import com.yugao.fintech.antelope.system.model.entity.SysRoleMenu;
import com.yugao.fintech.framework.assistant.utils.CollectionUtils;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class SysRoleMenuRelManager extends ServiceImpl<SysRoleMenuRelMapper, SysRoleMenu> {

    public List<SysRoleMenu> listByRoleId(Long roleId) {
        return this.list(SysRoleMenu.lqw().eq(SysRoleMenu::getRoleId, roleId));
    }

    public void deleteByRoleIdAndMenuIds(Long roleId, Collection<Long> menuIds) {
        if (CollectionUtils.isEmpty(menuIds) || Objects.isNull(roleId)) {
            return;
        }
        LambdaQueryWrapper<SysRoleMenu> lqw = SysRoleMenu.lqw().in(SysRoleMenu::getMenuId, menuIds)
                .eq(SysRoleMenu::getRoleId, roleId);
        this.remove(lqw);
    }

    public void deleteByMenuIds(Set<Long> menuIds) {
        LambdaQueryWrapper<SysRoleMenu> lqw = SysRoleMenu.lqw().in(SysRoleMenu::getMenuId, menuIds);
        this.remove(lqw);
    }

    public Set<Long> listRoleIdsByMenuId(Long menuId) {
        LambdaQueryWrapper<SysRoleMenu> lqw = SysRoleMenu.lqw().eq(SysRoleMenu::getMenuId, menuId);
        return this.list(lqw).stream().map(SysRoleMenu::getRoleId).collect(Collectors.toSet());
    }

    public void deleteByRoleIdAndActions(Long roleId, Set<String> actions) {
        LambdaQueryWrapper<SysRoleMenu> lqw = SysRoleMenu.lqw().eq(SysRoleMenu::getRoleId, roleId)
                .in(SysRoleMenu::getResourceAction, actions);
        this.remove(lqw);
    }

    public void updateAction(String oldAction, String newAction) {
        LambdaUpdateWrapper<SysRoleMenu> luw = SysRoleMenu.luw().eq(SysRoleMenu::getResourceAction, oldAction)
                .set(SysRoleMenu::getResourceAction, newAction);
        this.update(luw);
    }

    public List<Long> listMenuIdByRoleIds(List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<SysRoleMenu> lqw = SysRoleMenu.lqw()
                .in(SysRoleMenu::getRoleId, roleIds);
        return this.list(lqw).stream().map(SysRoleMenu::getMenuId).distinct().collect(Collectors.toList());

    }

    public Set<String> listActionsByRoleIds(List<Long> roleIds) {
        return this.list(SysRoleMenu.lqw().in(SysRoleMenu::getRoleId, roleIds).isNotNull(SysRoleMenu::getResourceAction))
                .stream().map(SysRoleMenu::getResourceAction).filter(StringUtils::isNotEmpty)
                .collect(Collectors.toSet());
    }
}
